package com.gateway.web.filter;

import com.gateway.common.constant.Constants;
import com.gateway.common.dto.ApiDefinition;
import com.gateway.common.enums.ApiStatusEnum;
import com.gateway.common.enums.AuthenticationTypeEnum;
import com.gateway.common.enums.AuthorizationTypeEnum;
import com.gateway.common.enums.GatewayRetCodeEnum;
import com.gateway.common.enums.RpcTypeEnum;
import com.gateway.plugin.api.util.WebFluxResultUtils;
import com.gateway.plugin.base.cache.ApiDataCache;
import com.gateway.web.exception.ApiException;
import org.springframework.http.server.PathContainer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * @program: api-gateway
 * @description:
 * @author: YuKai Fan
 * @create: 2025/2/10 21:10
 **/
public class ApiPathConvertFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        PathContainer pathContainer = request.getPath().pathWithinApplication();
        ApiDefinition apiDefinition = ApiDataCache.getInstance().obtain(pathContainer);
        if (Objects.isNull(apiDefinition)) {
            return WebFluxResultUtils.failedResult(GatewayRetCodeEnum.API_NOT_EXISTED, exchange);
        }
        ApiStatusEnum status = apiDefinition.getStatus();
        if (ApiStatusEnum.OFFLINE == status) {
            return WebFluxResultUtils.failedResult(GatewayRetCodeEnum.API_OFFLINE, exchange);
        }
        if (ApiStatusEnum.DISABLED == status) {
            return WebFluxResultUtils.failedResult(GatewayRetCodeEnum.API_BANNED, exchange);
        }
        exchange.getAttributes().put(Constants.API_DATA, apiDefinition);
        return chain.filter(exchange);
    }

}
